package com.sec.android.app.myfiles.launch;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileRecord;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.util.FileUtils;

public class HandleCompressFileImp extends AbsHandleLaunchImp {

    @Override
    public boolean isMyJob(Intent intent) {
        final String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            String type = intent.getType();
            return type != null && type.equals("application/zip");
        }
        return false;
    }

    @Override
    public boolean _handleStart(int processId, Activity activity, Intent intent) {
        boolean ret = false;
        if (NavigationManager.isPossibleToActionMode()) {
            String zipFilePath = intent.getStringExtra(AppConstants.INTENT_KEY_FILE_PATH);
            Uri uri = intent.getData();
            if ((uri != null) && (TextUtils.isEmpty(zipFilePath) || zipFilePath.startsWith("file://") || ContentResolver.SCHEME_FILE.equals(uri.getScheme()))) {
                zipFilePath = FileUtils.getFilePathFromUri(activity, uri, true);
            }
            if (!TextUtils.isEmpty(zipFilePath)) {
                ret = executeExternalCompressFile(processId, activity, zipFilePath, uri);
            } else {
                Toast.makeText(activity, R.string.unable_to_open_file, Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d(this, "can't handle compress file");
        }

        Log.d(this, "_handleStart ret " + ret);
        return ret;
    }

    protected boolean executeExternalCompressFile(int processId, Activity activity, String path, Uri uri) {
        boolean ret = false;
        if (!TextUtils.isEmpty(path)) {
            FileRecord record = new LocalFileRecord(path, uri);
            if (record != null) {
                if (record.exists(activity)) {
                    MyFilesFacade.executeRecord(processId, activity, record);
                } else {
                    Log.e(this, "executeExternalCompressFile - not exist:" + Log.getEncodedMsg(path));
                    Toast.makeText(activity, R.string.invalid_resource_path_specified, Toast.LENGTH_SHORT).show();
                    MyFilesFacade.goHome(processId, null, activity);
                }
                ret = true;
            }
        }
        return ret;
    }
}
